package ro.mfl.sockets.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MultiClient {

    private List<SocketClient> clients = new ArrayList<SocketClient>();

    public void createClients(int number) throws IOException {
        for (int i = 0; i < number; i++) {
            SocketClient c = SocketClient.create();
            clients.add(c);
        }
    }

    public void comm() throws  InterruptedException {
        for(SocketClient c : clients)
        {
            c.readMessage();
            c.sendMessage();
        }
    }

    public static void main(String[] args) {
        MultiClient m = new MultiClient();
        try {
            m.createClients(10);
            m.comm();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


}

class SocketClient {
    private Socket socket;
    private BufferedReader reader;
    private PrintWriter writer;
    private int messageNumber = 1;

    private SocketClient() {}

    static SocketClient create() {
        try {
            SocketClient client = new SocketClient();
            client.connect();
            return client;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    void connect() throws IOException {
        socket = new Socket("127.0.0.1", 9999);
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new PrintWriter(socket.getOutputStream(), true);
        writer.println(Thread.currentThread().getName());
    }

    void sendMessage() throws InterruptedException {
        Random random = new Random();
        int n = random.nextInt(10);
        Thread.sleep(n * 1000);
        writer.println(Thread.currentThread().getName() + " message " + messageNumber);
        messageNumber++;
    }

    void readMessage() throws InterruptedException {
        MessageReader messageReader = new MessageReader(reader);
        messageReader.start();
        messageReader.join();
    }

    private static class MessageReader extends Thread {
        BufferedReader reader;

        MessageReader(BufferedReader reader) {
            this.reader = reader;
        }

        public void run() {
            try {
                while (true) {
                    String line = reader.readLine();
                    System.out.println(line);
                    if(line.equalsIgnoreCase("QUIT"))
                        return;
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}